package com.globallogic.dailyplanner.utils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;


import com.globallogic.dailyplanner.dto.User;
import com.globallogic.dailyplanner.service.UserService;


@Component
@Scope("request")
public class UserNameValidator implements Validator{
        
        private static final String USERNAME_PATTERN = "^[a-zA-Z0-9_-]{3,15}$"; 
        
        @Autowired
        private UserService userService;
        private Pattern pattern;
        private Matcher matcher; 
        
        public UserNameValidator() {
                pattern = Pattern.compile(USERNAME_PATTERN);
                
        }


        @Override
        public void validate(FacesContext arg0, UIComponent arg1, Object value)
                        throws ValidatorException {
                String userName = value.toString();
                matcher = pattern.matcher(userName);
                
                if(!matcher.matches()){
                         
                        FacesMessage msg = 
                                new FacesMessage("Username validation failed.", 
                                                "Required 3-15 characters");
                        msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                        throw new ValidatorException(msg);
                }
                
                List<User> users = userService.getAll();
                
                if ( users != null){
                        for(User user: users){
                                //TODO: change equals to apache common lang.
                                if (userName.equals(user.getUsername())){
                                        FacesMessage msg = 
                                                        new FacesMessage("Username validation failed.", 
                                                                        "Such user has already exist.");
                                                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                                                throw new ValidatorException(msg);
                                }
                        }
                }
        }
}